//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Definitions;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Security;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI;
using DotNetNuke.UI.Modules;
using DotNetNuke.UI.Skins;
using DotNetNuke.Entities.Content;
using DotNetNuke.UI.Utilities;
namespace DotNetNuke.Modules.Admin.Modules
{
	partial class ModuleSettingsPage : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		private Control _Control;
		private new int ModuleId = -1;
		private new int TabModuleId = -1;
		private ModuleInfo _Module;
        private ModuleController _ModuleCtrl = null;
        private TabController _TabCtrl = null;
		private IDictionary<int, string> _TabsModulePaneInfo = null;
		protected ModuleInfo Module {
			get {
				if (_Module == null) {
					_Module = ModuleCtrl.GetModule(ModuleId, TabId, false);
				}
				return _Module;
			}
		}

        protected ModuleController ModuleCtrl
        {
            get
            {
                if ((_ModuleCtrl == null))
                {
                    _ModuleCtrl = new ModuleController();
                }
                return _ModuleCtrl;
            }
        }


		protected ISettingsControl SettingsControl {
			get { return _Control as ISettingsControl; }
		}

        protected TabController TabCtrl
        {
            get
            {
                if ((_TabCtrl == null))
                {
                    _TabCtrl = new TabController();
                }
                return _TabCtrl;
            }
        }

        private void AddCheckBoxConfirm(CheckBox chkBox, string confirmString)
        {
            chkBox.Attributes.Add("onClick", "javascript: if (!confirm('" + ClientAPI.GetSafeJSString(confirmString) + "')) return; else " + this.Page.ClientScript.GetPostBackEventReference(chkBox, "") + ";");
        }

		private void BindData()
		{
			if (Module != null) {
				DesktopModuleController objDeskMod = new DesktopModuleController();
				DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModule(Module.DesktopModuleID, PortalId);
				dgPermissions.ResourceFile = Common.Globals.ApplicationPath + "/DesktopModules/" + desktopModule.FolderName + "/" + Localization.LocalResourceDirectory + "/" + Localization.LocalSharedResourceFile;
				chkInheritPermissions.Checked = Module.InheritViewPermissions;
				dgPermissions.InheritViewPermissionsFromTab = Module.InheritViewPermissions;
				txtFriendlyName.Text = Module.DesktopModule.FriendlyName;
				txtTitle.Text = Module.ModuleTitle;
				ctlIcon.Url = Module.IconFile;
				if (cboTab.Items.FindByValue(Module.TabID.ToString()) != null) {
					cboTab.Items.FindByValue(Module.TabID.ToString()).Selected = true;
				}
				if (cboTab.Items.Count == 1) {
					rowTab.Visible = false;
				} else {
					rowTab.Visible = true;
				}
				chkAllTabs.Checked = Module.AllTabs;
				cboVisibility.SelectedIndex = (int)Module.Visibility;
				chkAdminBorder.Checked = Settings["hideadminborder"] != null ? bool.Parse(Settings["hideadminborder"].ToString()) : false;
				if (!IsPostBack) {
					BindInstalledOnPagesData();
				}
				ModuleDefinitionInfo objModuleDef = ModuleDefinitionController.GetModuleDefinitionByID(Module.ModuleDefID);
				if (objModuleDef.DefaultCacheTime == Null.NullInteger) {
					lblCacheDurationWarning.Visible = true;
					txtCacheDuration.Text = Module.CacheTime.ToString();
				} else {
					lblCacheDurationWarning.Visible = false;
					txtCacheDuration.Text = Module.CacheTime.ToString();
				}
				BindModuleCacheProviderList();
				ShowCacheRows();
				cboAlign.Items.FindByValue(Module.Alignment).Selected = true;
				txtColor.Text = Module.Color;
				txtBorder.Text = Module.Border;
				txtHeader.Text = Module.Header;
				txtFooter.Text = Module.Footer;
				if (!Null.IsNull(Module.StartDate)) {
					txtStartDate.Text = Module.StartDate.ToShortDateString();
				}
				if (!Null.IsNull(Module.EndDate)) {
					txtEndDate.Text = Module.EndDate.ToShortDateString();
				}
				ctlModuleContainer.SkinRoot = DotNetNuke.UI.Skins.SkinController.RootContainer;
				ctlModuleContainer.SkinSrc = Module.ContainerSrc;
				chkDisplayTitle.Checked = Module.DisplayTitle;
				chkDisplayPrint.Checked = Module.DisplayPrint;
				chkDisplaySyndicate.Checked = Module.DisplaySyndicate;
				chkWebSlice.Checked = Module.IsWebSlice;
				tblWebSlice.Visible = Module.IsWebSlice;
				txtWebSliceTitle.Text = Module.WebSliceTitle;
				if (!Null.IsNull(Module.WebSliceExpiryDate)) {
					txtWebSliceExpiry.Text = Module.WebSliceExpiryDate.ToShortDateString();
				}
				if (!Null.IsNull(Module.WebSliceTTL)) {
					txtWebSliceTTL.Text = Module.WebSliceTTL.ToString();
				}
				if (Module.ModuleID == DotNetNuke.Entities.Portals.PortalSettings.Current.DefaultModuleId && Module.TabID == DotNetNuke.Entities.Portals.PortalSettings.Current.DefaultTabId) {
					chkDefault.Checked = true;
				}
			}
		}
		private void BindInstalledOnPagesData()
		{
			lblInstalledOn.HelpText = Localization.GetString("InstalledOn.Help", this.LocalResourceFile);
			IDictionary<int, TabInfo> tabsByModule = TabCtrl.GetTabsByModuleID(ModuleId);
			tabsByModule.Remove(TabId);
			if ((tabsByModule.Count == 0)) {
				lstInstalledOnTabs.Visible = false;
				lblInstalledOn.Text = Localization.GetString("MsgInstalledOnNone", this.LocalResourceFile);
			} else {
				lstInstalledOnTabs.Visible = true;
				lblInstalledOn.Text = Localization.GetString("InstalledOn", this.LocalResourceFile);
				lstInstalledOnTabs.DataSource = tabsByModule.Values;
				lstInstalledOnTabs.DataBind();
			}
		}
		

        #region "Private Methods"

        private void BindModuleCacheProviderList()
        {
            cboCacheProvider.DataSource = GetFilteredProviders(DotNetNuke.Services.ModuleCache.ModuleCachingProvider.GetProviderList(), "ModuleCachingProvider");
            cboCacheProvider.DataBind();

            cboCacheProvider.Items.Insert(0, new ListItem(Localization.GetString("None_Specified"), ""));

            if (!string.IsNullOrEmpty(Module.GetEffectiveCacheMethod()) && cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()) != null)
            {
                cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()).Selected = true;
            }
            else
            {
                //select the None Specified value
                cboCacheProvider.Items[0].Selected = true;
            }

            lblCacheInherited.Visible = Module.CacheMethod != Module.GetEffectiveCacheMethod();
        }

        /// <summary>
        /// GetFilteredProviders takes a Dictionary and a string and returns an IEnumerable list
        /// where the key is modified by the filter string.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="providerList">A dictionary object containing the list of objects</param>
        /// <param name="keyFilter">A string used for filtering the key name</param>
        /// <returns>An enumeration with the modified and unmodified keys.</returns>
        /// <remarks></remarks>
        /// <history>
        ///     [jbrinkman]    11/17/2009  Initial release
        /// </history>
		private IEnumerable GetFilteredProviders<T>(Dictionary<string, T> providerList, string keyFilter)
		{
			var providers = from provider in providerList
							let filteredkey = provider.Key.Replace(keyFilter, String.Empty)
							select new
							{
								filteredkey,
								provider.Key
							};

			return providers;
		}

        private void ShowCacheRows()
        {
            if (!string.IsNullOrEmpty(cboCacheProvider.SelectedValue))
            {
                trCacheDuration.Visible = true;
            }
            else
            {
                trCacheDuration.Visible = false;
            }

        }

        #endregion


		protected string GetInstalledOnLink(object dataItem)
		{
			StringBuilder returnValue = new StringBuilder();
			if ((dataItem is Entities.Tabs.TabInfo)) {
				Entities.Tabs.TabInfo tab = (Entities.Tabs.TabInfo)dataItem;
				if ((tab != null)) {
					int index = 0;
					TabCtrl.PopulateBreadCrumbs(ref tab);
					foreach (Entities.Tabs.TabInfo t in tab.BreadCrumbs) {
						if ((index > 0)) {
							returnValue.Append(" > ");
						}
						if ((tab.BreadCrumbs.Count - 1 == index)) {
							returnValue.AppendFormat("<a href=\"{0}\">{1}</a>", t.FullUrl, t.LocalizedTabName);
						} else {
							returnValue.AppendFormat("{0}", t.LocalizedTabName);
						}
						index = index + 1;
					}
				}
			}
			return returnValue.ToString();
		}
		protected override void  OnInit(EventArgs e)
		{
 			 base.OnInit(e);
			ModuleController objModules = new ModuleController();
			ModuleControlInfo objModuleControlInfo;
			ArrayList arrModuleControls = new ArrayList();
			if ((Request.QueryString["ModuleId"] != null)) {
				ModuleId = Int32.Parse(Request.QueryString["ModuleId"]);
			}
            if (Module.ContentItemId == Null.NullInteger && Module.ModuleID != Null.NullInteger)
            {
                //This tab does not have a valid ContentItem
                objModules.CreateContentItem(Module);

                objModules.UpdateModule(Module);
            }
			if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "MANAGE", Module)) {
				Response.Redirect(Common.Globals.AccessDeniedURL(), true);
			}
			if (Module != null) {
				TabModuleId = Module.TabModuleID;
				objModuleControlInfo = ModuleControlController.GetModuleControlByControlKey("Settings", Module.ModuleDefID);
				if (objModuleControlInfo != null) {
					_Control = ControlUtilities.LoadControl<Control>(this.Page, objModuleControlInfo.ControlSrc);
					ISettingsControl SettingsControl = _Control as ISettingsControl;
					if (SettingsControl != null) {
						_Control.ID = System.IO.Path.GetFileNameWithoutExtension(objModuleControlInfo.ControlSrc).Replace('.', '-');
						SettingsControl.ModuleContext.Configuration = Module;
						dshSpecific.Text = Localization.GetString("ControlTitle_settings", SettingsControl.LocalResourceFile);
						pnlSpecific.Controls.Add(_Control);
						if (!String.IsNullOrEmpty(Localization.GetString(Entities.Modules.Actions.ModuleActionType.HelpText, SettingsControl.LocalResourceFile))) {
							rowspecifichelp.Visible = true;
							imgSpecificHelp.AlternateText = Localization.GetString(Entities.Modules.Actions.ModuleActionType.ModuleHelp, Localization.GlobalResourceFile);
							lnkSpecificHelp.Text = Localization.GetString(Entities.Modules.Actions.ModuleActionType.ModuleHelp, Localization.GlobalResourceFile);
							lnkSpecificHelp.NavigateUrl = Common.Globals.NavigateURL(TabId, "Help", "ctlid=" + objModuleControlInfo.ModuleControlID.ToString(), "moduleid=" + ModuleId);
						} else {
							rowspecifichelp.Visible = false;
						}
					}
				}
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			chkAllTabs.CheckedChanged += new EventHandler(chkAllTabs_CheckedChanged);
			chkInheritPermissions.CheckedChanged += new EventHandler(chkInheritPermissions_CheckedChanged);
			chkWebSlice.CheckedChanged += new EventHandler(chkWebSlice_CheckedChanged);
			cboCacheProvider.TextChanged += new EventHandler(cboCacheProvider_Change);
			cmdCancel.Click += new EventHandler(cmdCancel_Click);
			cmdDelete.Click += new EventHandler(cmdDelete_Click);
			cmdUpdate.Click += new EventHandler(cmdUpdate_Click);
			lstInstalledOnTabs.PageIndexChanged += new DataGridPageChangedEventHandler(lstInstalledOnTabs_PageIndexChanged);

			try {
				cmdStartCalendar.NavigateUrl = Common.Utilities.Calendar.InvokePopupCal(txtStartDate);
				cmdEndCalendar.NavigateUrl = Common.Utilities.Calendar.InvokePopupCal(txtEndDate);
				cmdWebSliceExpiry.NavigateUrl = Common.Utilities.Calendar.InvokePopupCal(txtWebSliceExpiry);
				if (ModuleId != -1) {
					ctlAudit.Entity = Module;
				}
				if (Page.IsPostBack == false) {
					ctlIcon.FileFilter = Common.Globals.glbImageFileTypes;
					dgPermissions.TabId = PortalSettings.ActiveTab.TabID;
					dgPermissions.ModuleID = ModuleId;
					DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(cmdDelete, Localization.GetString("DeleteItem"));
					cboTab.DataSource = TabController.GetPortalTabs(PortalId, -1, false, Null.NullString, true, false, true, false, true);
					cboTab.DataBind();
					if (PortalSettings.ActiveTab.ParentId == PortalSettings.SuperTabId) {
						cboTab.Items.Insert(0, new ListItem(PortalSettings.ActiveTab.LocalizedTabName, PortalSettings.ActiveTab.TabID.ToString()));
					}
					if (Module != null) {
						if (cboTab.Items.FindByValue(Module.TabID.ToString()) == null) {
							TabController objtabs = new TabController();
							TabInfo objTab = objtabs.GetTab(Module.TabID, PortalId, false);
							cboTab.Items.Add(new ListItem(objTab.LocalizedTabName, objTab.TabID.ToString()));
						}
					}
					trAllTabs.Visible = PortalSecurity.IsInRole("Administrators");
					if (!TabPermissionController.CanAdminPage()) {
						chkAllModules.Enabled = false;
						chkDefault.Enabled = false;
						cboTab.Enabled = false;
					}
					if (ModuleId != -1) {
						BindData();
						cmdDelete.Visible = ModulePermissionController.CanDeleteModule(Module) || TabPermissionController.CanAddContentToPage();
					} else {
						cboVisibility.SelectedIndex = 0;
						chkAllTabs.Checked = false;
						cmdDelete.Visible = false;
					}
					cmdUpdate.Visible = ModulePermissionController.HasModulePermission(Module.ModulePermissions, "EDIT,MANAGE") || TabPermissionController.CanAddContentToPage();
					rowPerm.Visible = ModulePermissionController.CanAdminModule(Module) || TabPermissionController.CanAddContentToPage();
					if (SettingsControl == null == false) {
						SettingsControl.LoadSettings();
						dshSpecific.Visible = true;
						tblSpecific.Visible = true;
					} else {
						dshSpecific.Visible = false;
						tblSpecific.Visible = false;
					}

                    termsSelector.PortalId = Module.PortalID;
                    termsSelector.Terms = Module.Terms;
                    termsSelector.DataBind();
				}
                cultureLanguageLabel.Language = Module.CultureCode;
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		protected void chkAllTabs_CheckedChanged(object sender, System.EventArgs e)
		{
			if ((!Module.AllTabs == chkAllTabs.Checked)) {
				trnewPages.Visible = chkAllTabs.Checked;
			}
		}
		private void chkInheritPermissions_CheckedChanged(System.Object sender, System.EventArgs e)
		{
			if (chkInheritPermissions.Checked) {
				dgPermissions.InheritViewPermissionsFromTab = true;
			} else {
				dgPermissions.InheritViewPermissionsFromTab = false;
			}
		}
		protected void chkWebSlice_CheckedChanged(object sender, System.EventArgs e)
		{
			tblWebSlice.Visible = chkWebSlice.Checked;
		}
		protected void cboCacheProvider_Change(object sender, System.EventArgs e)
		{
			ShowCacheRows();
		}
		private void cmdCancel_Click(System.Object sender, System.EventArgs e)
		{
			try {
				Response.Redirect(Common.Globals.NavigateURL(), true);
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdDelete_Click(System.Object sender, System.EventArgs e)
		{
			try {
				ModuleController objModules = new ModuleController();
				objModules.DeleteTabModule(TabId, ModuleId, true);
				Response.Redirect(Common.Globals.NavigateURL(), true);
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdUpdate_Click(object Sender, EventArgs e)
		{
			try {
				if (Page.IsValid) {
					ModuleController objModules = new ModuleController();
					bool AllTabsChanged = false;
					if (!TabPermissionController.CanAdminPage()) {
						chkAllTabs.Enabled = false;
						chkDefault.Enabled = false;
						chkAllModules.Enabled = false;
						cboTab.Enabled = false;
					}
				    Module.ModuleID = ModuleId;
                    Module.ModuleTitle = txtTitle.Text;
                    Module.Alignment = cboAlign.SelectedItem.Value;
                    Module.Color = txtColor.Text;
                    Module.Border = txtBorder.Text;
                    Module.IconFile = ctlIcon.Url;
					if (!String.IsNullOrEmpty(txtCacheDuration.Text)) {
                        Module.CacheTime = Int32.Parse(txtCacheDuration.Text);
					} else {
                        Module.CacheTime = 0;
					}
                    Module.CacheMethod = cboCacheProvider.SelectedValue;
                    Module.TabID = TabId;
                    if (Module.AllTabs != chkAllTabs.Checked)
                    {
						AllTabsChanged = true;
					}
                    Module.AllTabs = chkAllTabs.Checked;
					objModules.UpdateTabModuleSetting(Module.TabModuleID, "hideadminborder", chkAdminBorder.Checked.ToString());
					switch (Int32.Parse(cboVisibility.SelectedItem.Value)) {
						case 0:
                            Module.Visibility = VisibilityState.Maximized;
							break;
						case 1:
                            Module.Visibility = VisibilityState.Minimized;
							break;
						case 2:
                            Module.Visibility = VisibilityState.None;
							break;
					}
                    Module.IsDeleted = false;
                    Module.Header = txtHeader.Text;
                    Module.Footer = txtFooter.Text;
					if (!string.IsNullOrEmpty(txtStartDate.Text)) {
                        Module.StartDate = Convert.ToDateTime(txtStartDate.Text);
					} else {
                        Module.StartDate = Null.NullDate;
					}
					if (!string.IsNullOrEmpty(txtEndDate.Text)) {
                        Module.EndDate = Convert.ToDateTime(txtEndDate.Text);
					} else {
                        Module.EndDate = Null.NullDate;
					}
                    Module.ContainerSrc = ctlModuleContainer.SkinSrc;
                    Module.ModulePermissions.Clear();
                    Module.ModulePermissions.AddRange(dgPermissions.Permissions);
                    Module.Terms.Clear();
                    Module.Terms.AddRange(termsSelector.Terms);
                    Module.InheritViewPermissions = chkInheritPermissions.Checked;
                    Module.DisplayTitle = chkDisplayTitle.Checked;
                    Module.DisplayPrint = chkDisplayPrint.Checked;
                    Module.DisplaySyndicate = chkDisplaySyndicate.Checked;
                    Module.IsWebSlice = chkWebSlice.Checked;
                    Module.WebSliceTitle = txtWebSliceTitle.Text;
					if (!string.IsNullOrEmpty(txtWebSliceExpiry.Text)) {
                        Module.WebSliceExpiryDate = Convert.ToDateTime(txtWebSliceExpiry.Text);
					} else {
                        Module.WebSliceExpiryDate = Null.NullDate;
					}
					if (!string.IsNullOrEmpty(txtWebSliceTTL.Text)) {
                        Module.WebSliceTTL = Convert.ToInt32(txtWebSliceTTL.Text);
					}
                    Module.IsDefaultModule = chkDefault.Checked;
                    Module.AllModules = chkAllModules.Checked;
                    objModules.UpdateModule(Module);
					if (SettingsControl != null) {
						try {
							SettingsControl.UpdateSettings();
						} catch (System.Threading.ThreadAbortException ex) {
							System.Threading.Thread.ResetAbort();
						} catch (Exception ex) {
							DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
						}
					}
					if (!chkAllTabs.Checked) {
						int newTabId = Int32.Parse(cboTab.SelectedItem.Value);
						if (TabId != newTabId) {
							ModuleInfo tmpModule = objModules.GetModule(ModuleId, newTabId);
							if (tmpModule == null) {
								objModules.MoveModule(ModuleId, TabId, newTabId, "");
							} else {
								DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ModuleExists", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
								return;
							}
						}
					}
					if (AllTabsChanged) {
						List<Entities.Tabs.TabInfo> listTabs = TabController.GetPortalTabs(PortalSettings.PortalId, Null.NullInteger, false, true);
						if (chkAllTabs.Checked) {
							if (!chkNewTabs.Checked) {
								foreach(TabInfo destinationTab in listTabs)
                                {
                                    objModules.CopyModule(Module, destinationTab, Null.NullString, true);
                                }
							}
						} else {
							objModules.DeleteAllModules(ModuleId, TabId, listTabs);
						}
					}
					Response.Redirect(Common.Globals.NavigateURL(), true);
				}
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		protected void lstInstalledOnTabs_PageIndexChanged(object sender, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
		{
			try {
				lstInstalledOnTabs.CurrentPageIndex = e.NewPageIndex;
				BindInstalledOnPagesData();
			} catch (Exception ex) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
			}
		}
	}
}
